<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2015 http://www.youdi365.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author:  心云间、凝听 <981248356@qq.com>
// +----------------------------------------------------------------------
namespace Admin\Controller;

use Admin\Builder\AdminFormBuilder;
use Admin\Builder\AdminListBuilder;
class AttachmentController extends AdminController {
    //附件管理
    protected $attachmentModel;

    function _initialize()
    {
        parent::_initialize();
        $this->attachmentModel = D('Attachment');
    }
    //附件首页
    public function index(){
    	$this->meta_title ='附件管理';
        $paged=I('p',1,'intval');
        $map['status']=1;
        list($file_list,$page_totalCount)=$this->attachmentModel->getListByPage($map,$paged,$order='sort asc,update_time desc',$field='*',$r=24);
        $this->assign('attachment_list_data',$file_list);//附件列表数据
        $page = new \Think\Page($page_totalCount,$r=24);
        $this->assign('table_data_page',$page->show());
    	$this->display();
    }

    /**
     * 获取附件信息
     * @param  int $id id
     * @author 心云间、凝听 <981248356@qq.com>
     */
    public function attachmentInfo($id){
        $return=$this->attachmentModel->find($id);
        $return['type']='image/'.$return['ext'];
        $return['uploadtime']=date('Y-m-d H:i:s',$return['create_time']);
        $return['url']='http://'.$_SERVER['HTTP_HOST'].get_pic_src($return['path']);
        $return['author']=get_user_info($return['uid'],'nickname')['nickname'];
        $this->ajaxReturn($return);
    }
       /**
     * 编辑附件信息
     * @param  int $id id
     * @author 心云间、凝听 <981248356@qq.com>
     */
    public function editAttachment($data=array()){
        $data['id']=I('post.id');
        $data['alt']=I('post.alt');
        $result=$this->attachmentModel->save($data);
        if ($result) {
            $this->success('更新成功',U('index'));
        }else{
            $this->error('更新失败', $this->attachmentModel->getError());
        }
    }
    /**
     * 删除附件
     * @param  int $id id
     * @author 心云间、凝听 <981248356@qq.com>
     */
    public function delAttachment($id){
        $attachmentInfo=$this->attachmentModel->find($id);
        $realpath = realpath('.'.getRootUrl().$attachmentInfo['path']);
        if ($realpath&&$attachmentInfo['location']=='local') {
            if (@unlink($realpath)===false) {
                $this->error('删除失败！');
            } else {
                $resut =$this->attachmentModel->delete($id);
                $this->success('删除成功！');
            }
        } else {//属于无效文件
            $resut = $this->attachmentModel->delete($id);
            $this->success('删除成功！');
        }

    }
    /**
     * 附件分类
     * @param  int $id id
     * @author 心云间、凝听 <981248356@qq.com>
     */
    public function attachmentCategory(){
        $this->meta_title ='附件分类';
        // 获取所有用户
        $map['status'] = array('egt', '0','1'); // 发布和不发布状态
        $map['taxonomy'] = 'attachment_category';
        $tab_list=array(
                array('title'=>'媒体文件','href'=>U('index')),
                array('title'=>'附件分类','href'=>U('attachmentCategory')),
                array('title'=>'设置','href'=>U('setting'))
            );
        $paged=I('get.p/d',1);
        list($data_list,$totalCount) = D('terms')->getListByPage($map,$paged,'sort desc,create_time desc','*',20);
        // 使用Builder快速建立列表页面。
        $builder = new AdminListBuilder();
        $builder->setMetaTitle('分类管理') // 设置页面标题
                ->addTopButton('addnew')  // 添加新增按钮
                ->addTopButton('resume')  // 添加启用按钮
                ->addTopButton('forbid')  // 添加禁用按钮
                ->addTopButton('recycle') //添加回收按钮
                ->setTabNav($tab_list)  // 设置页面Tab导航
                ->setSearch('输入分类名称', U('index'))
                ->keyListItem('name', '名称','link',U('edit',array('term_id'=>'__data_id__')))
                ->keyListItem('slug', '别名')
                ->keyListItem('term_id', '文章数','callback', array(D('terms'),'term_relation_count'))
                ->keyListItem('status', '状态', 'status')
                ->keyListItem('right_button', '操作', 'btn')
                ->setListDataKey('term_id')
                ->setListData($data_list)    // 数据列表
                ->setListPage($totalCount,20) // 数据列表分页
                ->addRightButton('edit')// 添加编辑按钮
                ->addRightButton('recycle')// 添加删除按钮
                ->display();

    }
    //设置
    public function setting(){
        $this->meta_title ='设置';
        $this->display();
    }    
    /* 文件上传 */
    public function upload(){
        $return  = array('status' => 1, 'info' =>'上传成功', 'data' => '');
        /* 调用文件上传组件上传文件 */
        $File = D('File');
        $file_driver = C('DOWNLOAD_UPLOAD_DRIVER');
        $info = $File->upload(
            $_FILES,
            C('DOWNLOAD_UPLOAD'),
            C('DOWNLOAD_UPLOAD_DRIVER'),
            C("UPLOAD_{$file_driver}_CONFIG")
        );

        /* 记录附件信息 */
        if($info){
            $return['data'] = think_encrypt(json_encode($info['download']));
            $return['info'] = $info['download']['name'];
        } else {
            $return['status'] = 0;
            $return['info']   = $File->getError();
        }

        /* 返回JSON数据 */
        $this->ajaxReturn($return);
    }

    /* 下载文件 */
    public function download($id = null){
        if(empty($id) || !is_numeric($id)){
            $this->error(L('_PARAMETER_ERROR_'));
        }

        $logic = D('Download', 'Logic');
        if(!$logic->download($id)){
            $this->error($logic->getError());
        }

    }

    /**
     * 上传图片
     * @author huajie <banhuajie@163.com>
     */
    public function uploadPicture(){
        //TODO: 用户登录检测

        /* 返回标准数据 */
        $return  = array('status' => 1, 'info' =>'上传成功', 'data' => '');

        $driver ='./Uploads/Picture/';//图片保存路径
        $driver = check_driver_is_exist($driver);
        $uploadConfig = get_upload_config($driver);

        $info = $this->attachmentModel->upload(
                        $_FILES,
                        C('PICTURE_UPLOAD'),
                        $driver,
                        $uploadConfig
                    ); //TODO:上传到远程服务器
        /* 记录图片信息 */
        if($info){
            $return['status'] = 1;
            $return = array_merge($info, $return);
        } else {
            $return['status'] = 0;
            $return['info'] = $this->attachmentModel->getError();
        }
        //dump($return);
        /* 返回JSON数据 */
        $this->ajaxReturn($return);
    }

    /**用于兼容UM编辑器的图片上传方法
     * @auth 陈一枭
     */
    public function uploadPictureUM()
    {
        header("Content-Type:text/html;charset=utf-8");
        //TODO: 用户登录检测
        /* 返回标准数据 */
        $return = array('status' => 1, 'info' => '上传成功', 'data' => '');

        //实际有用的数据只有name和state，这边伪造一堆数据保证格式正确
        $originalName = 'u=2830036734,2219770442&fm=21&gp=0.jpg';
        $newFilename = '14035912861705.jpg';
        $filePath = 'upload\/20140624\/14035912861705.jpg';
        $size = '7446';
        $type = '.jpg';
        $status = 'success';
        $rs = array(
            "originalName" => $originalName,
            'name' => $newFilename,
            'url' => $filePath,
            'size' => $size,
            'type' => $type,
            'state' => $status,
            'original' => $_FILES['upfile']['name']
        );

        $setting = C('EDITOR_UPLOAD');
        $setting['rootPath']='./Uploads/Editor/Picture/';

        //$driver = modC('PICTURE_UPLOAD_DRIVER','local','config');
        $driver ='./Uploads/Editor/Picture/';//图片保存路径
        $driver = check_driver_is_exist($driver);
        $uploadConfig = get_upload_config($driver);

        $info = $this->attachmentModel->upload(
            $_FILES,
            $setting,
            $driver,
            $uploadConfig
        ); //TODO:上传到远程服务器

        /* 记录图片信息 */
        if ($info) {
            $return['status'] = 1;
            if ($info['Filedata']) {
                $return = array_merge($info['Filedata'], $return);
            }
            if ($info['download']) {
                $return = array_merge($info['download'], $return);
            }
            $rs['state'] = 'SUCCESS';
            $rs['url'] = get_pic_src($info['path']);
            if ($type == 'ajax') {
                echo json_encode($rs);
                exit;
            } else {
                echo json_encode($rs);
                exit;
            }

        } else {
            $return['state'] = 0;
            $return['info'] = $this->attachmentModel->getError();
        }

        /* 返回JSON数据 */
        $this->ajaxReturn($return);
    }


    public function uploadFileUE(){
        $return = array('status' => 1, 'info' =>'上传成功', 'data' => '');

        //实际有用的数据只有name和state，这边伪造一堆数据保证格式正确
        $originalName = 'u=2830036734,2219770442&fm=21&gp=0.jpg';
        $newFilename = '14035912861705.jpg';
        $filePath = 'upload\/20140624\/14035912861705.jpg';
        $size = '7446';
        $type = '.jpg';
        $status = 'success';
        $rs = array(
            'name' => $newFilename,
            'url' => $filePath,
            'size' => $size,
            'type' => $type,
            'state' => $status
        );

        /* 调用文件上传组件上传文件 */
        $File = D('File');

       // $driver = modC('DOWNLOAD_UPLOAD_DRIVER','local','config');
        $driver ='./Uploads/Editor/File/';//图片保存路径
        $driver = check_driver_is_exist($driver);
        $uploadConfig = get_upload_config($driver);

        $setting = C('EDITOR_UPLOAD');
        $setting['rootPath']='./Uploads/Editor/File/';


        $setting['exts'] = 'jpg,gif,png,jpeg,zip,rar,tar,gz,7z,doc,docx,txt,xml,xlsx,xls,ppt,pptx,pdf';
        $info = $File->upload(
            $_FILES,
            $setting,
            $driver,
            $uploadConfig
        );

        /* 记录附件信息 */
        if ($info) {
            $return['data'] = $info;

            $rs['original'] = $info['name'];
            $rs['state'] = 'SUCCESS';
            $rs['url'] =  strpos($info['savepath'], 'http://') === false ?  __ROOT__.$info['savepath'].$info['savename']:$info['savepath'];
            $rs['size'] = $info['size'];
            $rs['title'] = $info['savename'];


            if ($type == 'ajax') {
                echo json_encode($rs);
                exit;
            } else {
                echo json_encode($rs);
                exit;
            }

        } else {
            $return['status'] = 0;
            $return['info'] = $File->getError();
        }

        /* 返回JSON数据 */
        $this->ajaxReturn($return);
    }


    public function uploadAvatar(){

        $aUid = I('get.uid',0,'intval');

        mkdir ("./Uploads/Avatar/".$aUid);


        $files = $_FILES;
        $setting  = C('PICTURE_UPLOAD');

        $driver = modC('PICTURE_UPLOAD_DRIVER','local','config');
        $driver = check_driver_is_exist($driver);
        $uploadConfig = get_upload_config($driver);


        /* 上传文件 */
        $setting['rootPath'] = './Uploads/Avatar';
        $setting['saveName'] = array('uniqid', '/'.$aUid.'/');
        $setting['savepath'] = '';
        $setting['subName'] = '';
        $setting['replace'] = true;

        //sae下
        if (strtolower(C('PICTURE_UPLOAD_DRIVER'))  == 'sae') {
            // $config[]
            C(require_once(APP_PATH . 'Common/Conf/config_sae.php'));

            $Upload = new \Think\Upload($setting,C('PICTURE_UPLOAD_DRIVER'), array(C('UPLOAD_SAE_CONFIG')));
            $info = $Upload->upload($files);

            $config=C('UPLOAD_SAE_CONFIG');
            if ($info) { //文件上传成功，记录文件信息
                foreach ($info as $key => &$value) {
                    $value['path'] = $config['rootPath'] . 'Avatar/' . $value['savepath'] . $value['savename']; //在模板里的url路径

                }
                /* 设置文件保存位置 */
                $this->_auto[] = array('location', 'Ftp' === $driver ? 1 : 0, self::MODEL_INSERT);
            }
        }else{
            $Upload = new \Think\Upload($setting, $driver, $uploadConfig);
            $info = $Upload->upload($files);
        }
        if ($info) { //文件上传成功，不记录文件
            $return['status'] = 1;
            if ($info['Filedata']) {
                $return = array_merge($info['Filedata'], $return);
            }
            if ($info['download']) {
                $return = array_merge($info['download'], $return);
            }
            /*适用于自动表单的图片上传方式*/
            if ($info['file']) {
                $return['data']['file'] = $info['file'];

                $path = $info['file']['url'] ? $info['file']['url'] : "./Uploads/Avatar".$info['file']['savename'];
                $src = $info['file']['url'] ? $info['file']['url'] : __ROOT__."/Uploads/Avatar".$info['file']['savename'];
               // $return['data']['file']['path'] =;
                $return['data']['file']['path'] =$path;
                $return['data']['file']['src']=$src;
                $size =  getimagesize($path);
                $return['data']['file']['width'] =$size[0];
                $return['data']['file']['height'] =$size[1];
                $return['data']['file']['time'] =time();
            }
        } else {
            $return['status'] = 0;
            $return['info'] = $Upload->getError();
        }

        $this->ajaxReturn($return);
    }

    public function uploadPictureBase64()
    {

        $aData = $_POST['data'];

        if ($aData == '' || $aData == 'undefined') {
            $this->ajaxReturn(array('status'=>0,'info'=>'参数错误'));
        }

        if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $aData, $result)) {
            $base64_body = substr(strstr($aData, ','), 1);

            empty($aExt) && $aExt = $result[2];
        } else {
            $base64_body = $aData;
        }

        empty($aExt) && $aExt = 'jpg';


        $md5 = md5($base64_body);
        $sha1 = sha1($base64_body);


        $check = $this->attachmentModel->where(array('md5' => $md5, 'sha1' => $sha1))->find();

        if ($check) {
            //已存在则直接返回信息
            $return['id'] = $check['id'];
            $return['path'] = render_picture_path($check['path']);
            $this->ajaxReturn(array('status'=>1,'id'=>$return['id'],'path'=> $return['path']));
        } else {
            //不存在则上传并返回信息
            $driver = modC('PICTURE_UPLOAD_DRIVER','local','config');
            $driver = check_driver_is_exist($driver);
            $date = date('Y-m-d');
            $saveName = uniqid();
            $savePath = '/Uploads/Picture/' . $date . '/';

            $path = $savePath . $saveName . '.' . $aExt;
            if($driver == 'local'){
                //本地上传
                mkdir('.' . $savePath, 0777, true);
                $data = base64_decode($base64_body);
                $rs = file_put_contents('.' . $path, $data);
            }
            else{
                $rs = false;
                //使用云存储
                $name = get_addon_class($driver);
                if (class_exists($name)) {
                    $class = new $name();
                    if (method_exists($class, 'uploadBase64')) {
                        $path = $class->uploadBase64($base64_body,$path);
                        $rs = true;
                    }
                }
            }
            if ($rs) {
                $pic['type'] = $driver;
                $pic['path'] = $path;
                $pic['md5'] = $md5;
                $pic['sha1'] = $sha1;
                $pic['status'] = 1;
                $pic['create_time'] = time();
                $id = $this->attachmentModel->add($pic);
               $this->ajaxReturn (array('status'=>1,'id' => $id, 'path' => render_picture_path($path)));
            } else {
                $this->ajaxReturn(array('status'=>0,'图片上传失败。'));
            }

        }
    }
}